/**
 * 任务数据模型
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-08-28 08:00:00 
 */

const BaseModel = require('./base_model.js');

class TaskModel extends BaseModel {

	/**
	 * 构造函数
	 */
	constructor() {
		super();

		this._projectId = 'task_project_id';
		this._table = 'plm_task';
		this._transactionCollection = 'plm_task,plm_project';
	}

	/**
	 * 获取任务的数据结构
	 */
	getTaskSchema() {
		return {
			task_id: 'string|required',           // 任务ID
			task_title: 'string|required',        // 任务标题 
			task_desc: 'string',                  // 任务描述
			task_project_id: 'string|required',   // 关联项目ID
			task_project_title: 'string',         // 关联项目标题(冗余)
			task_project_status: 'string',        // 关联项目状态
			task_priority: 'int|required',        // 优先级 1-10
			task_required: 'bool|required',       // 是否必须完成
			task_status: 'int|required',          // 状态 0未开始 1进行中 2已完成 3已取消
			task_progress: 'int|required',        // 进度 0-100
			task_assign: 'string',                // 指派人ID
			task_assign_name: 'string',           // 指派人名称(冗余)
			task_assign_time: 'int',              // 指派时间
			task_start_time: 'int',               // 开始时间
			task_end_time: 'int',                 // 结束时间
			task_complete_time: 'int',            // 完成时间
			task_cancel_time: 'int',              // 取消时间
			task_create_time: 'int|required',     // 创建时间
			task_update_time: 'int',              // 最后更新时间
			task_add_time: 'int',                 // 添加时间
			task_add_ip: 'string',                // 添加IP
			task_edit_time: 'int',                // 修改时间
			task_edit_ip: 'string'                // 修改IP
		}
	}

	/**
	 * 获取任务的显示字段
	 */
	getTaskFields() {
		return '*';
	}

	/**
	 * 查询我的任务列表
	 */
	async getMyTaskList({userId, search, sortType, sortVal, page, size, status}) {
		let where = {
			task_assign: userId
		};
		
		if (status !== undefined && status !== null) {
			where.task_status = status;
		}
		
		if (search) {
			where.task_title = {
				$regex: '.*' + search + '.*',
				$options: 'i'
			};
		}
		
		let orderBy = {};
		if (sortType && sortVal !== undefined) {
			orderBy[sortType] = sortVal;
		} else {
			orderBy = {
				'task_priority': -1,
				'task_create_time': -1
			};
		}
		
		return await this.getList(where, this.getTaskFields(), orderBy, page, size);
	}

	/**
	 * 根据项目ID查询任务列表
	 */
	async getProjectTaskList({projectId, search, sortType, sortVal, page, size, status}) {
		let where = {
			task_project_id: projectId
		};
		
		if (status !== undefined && status !== null) {
			where.task_status = status;
		}
		
		if (search) {
			where.task_title = {
				$regex: '.*' + search + '.*',
				$options: 'i'
			};
		}
		
		let orderBy = {};
		if (sortType && sortVal !== undefined) {
			orderBy[sortType] = sortVal;
		} else {
			orderBy = {
				'task_priority': -1,
				'task_create_time': -1
			};
		}
		
		return await this.getList(where, this.getTaskFields(), orderBy, page, size);
	}

	/**
	 * 根据项目ID获取任务统计数据
	 */
	async getTaskStatsByProjectId(projectId) {
		const where = {
			task_project_id: projectId
		};
		
		const stats = {
			total: 0,         // 任务总数
			notStarted: 0,    // 未开始
			inProgress: 0,    // 进行中
			completed: 0,     // 已完成
			cancelled: 0,     // 已取消
			requiredTotal: 0, // 必要任务总数
			requiredCompleted: 0 // 已完成的必要任务数
		};
		
		// 获取总数
		stats.total = await this.count(where);
		
		// 获取各状态任务数
		stats.notStarted = await this.count({...where, task_status: 0});
		stats.inProgress = await this.count({...where, task_status: 1});
		stats.completed = await this.count({...where, task_status: 2});
		stats.cancelled = await this.count({...where, task_status: 3});
		
		// 获取必要任务相关统计
		stats.requiredTotal = await this.count({...where, task_required: true});
		stats.requiredCompleted = await this.count({...where, task_required: true, task_status: 2});
		
		return stats;
	}

	/**
	 * 根据项目状态获取必须完成的任务
	 */
	async getRequiredTasksByProjectStatus(projectId, projectStatus) {
		const where = {
			task_project_id: projectId,
			task_project_status: projectStatus,
			task_required: true
		};
		
		return await this.getAll(where, this.getTaskFields());
	}

	/**
	 * 批量添加任务
	 */
	async insertBatch(tasks) {
		return await this.insertMany(tasks);
	}

	/**
	 * 更新任务状态和进度
	 */
	async updateTaskStatusAndProgress(taskId, status, progress, userId, updateTime) {
		const data = {
			task_status: status,
			task_progress: progress,
			task_update_time: updateTime
		};
		
		// 根据状态设置相应的时间字段
		if (status === 2) { // 已完成
			data.task_complete_time = updateTime;
		} else if (status === 3) { // 已取消
			data.task_cancel_time = updateTime;
		}
		
		const where = {
			_id: taskId
		};
		
		return await this.edit(where, data);
	}

	/**
	 * 删除项目相关的所有任务
	 */
	async deleteProjectTasks(projectId) {
		const where = {
			task_project_id: projectId
		};
		
		return await this.del(where);
	}
}

module.exports = TaskModel; 